# coding: utf-8
import json
import codecs
import os
import click

class MergedSettings(object):

    def __init__(self, setting_list):
        # [local, global]
        self.setting_list = setting_list
    
    def get(self, key):
        for setting in self.setting_list:
            if setting.has(key):
                return setting.get(key)
        raise Exception('No {} in the settings!'.format(key))
    
    def set(self, key, value):
        for setting in self.setting_list:
            if setting.has(key):
                setting.set(key, value)
                return
        # 不能设置没有的
        raise Exception('No {} in the settings!'.format(key))
    
    def has(self, key):
        for setting in self.setting_list:
            if setting.has(key):
                return True
        return False
            
        

class FileSettings(object):

    def __init__(self, settings_path):
        with codecs.open(settings_path, encoding='utf-8') as f:
            self.settings = json.load(f)
        self.settings_path = settings_path
    
    @staticmethod
    def make_if_not_exists(dirname):
        settings_dir = os.path.join(dirname, '.philly')
        settings_file = os.path.join(settings_dir, 'settings')
        if not(os.path.exists(settings_file)):
            if not(os.path.exists(settings_dir)):
                os.makedirs(settings_dir)
            with open(settings_file, 'w') as f:
                f.write('{}')
    
    def get(self, key):
        if key in self.settings:
            return self.settings[key]
        else:
            raise Exception('No {} in the settings!'.format(key))
    
    def set(self, key, value):
        self.settings[key] = value
        with codecs.open(self.settings_path, 'w', encoding='utf-8') as f:
            json.dump(self.settings, f)
    
    def has(self, key):
        return key in self.settings